package com.haizi.battery.controller.battery;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haizi.battery.entity.battery.RealTimeData;
import com.haizi.battery.gate.core.evgb.entity.UpdateBms;
import com.haizi.battery.gate.server.handler.UpdateHandler;
import com.haizi.battery.service.battery.RealTimeDataService;
import com.haizi.battery.utils.R;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 储能站
 * </p>
 *
 * @author HaiziGe
 * @date 2020-07-27 16:19:04
 */
@RestController
@AllArgsConstructor
@RequestMapping("/realtime")
public class RealTimeDataController {

    private final RealTimeDataService realTimeDataService;


    private final UpdateHandler updateHandler;

    @PostMapping
    public R save(@RequestBody RealTimeData realTimeData) {
        boolean save = realTimeDataService.save(realTimeData);
        if (save) {
            return R.ok(true);
        } else {
            return R.error("VIN不可重复");
        }

    }

    @GetMapping("/count")
    public R getCountNow() {
        return R.ok(realTimeDataService.getCountNow());
    }

    @DeleteMapping("/{id}")
    public R delete(@PathVariable("id") Integer id) {
        return R.ok(realTimeDataService.removeById(id));
    }

    @PutMapping
    public R update(@RequestBody RealTimeData realTimeData) {
        return R.ok(realTimeDataService.updateById(realTimeData));
    }

    @GetMapping
    public R page(Page page, RealTimeData realTimeData) {
        if (StrUtil.isEmpty(realTimeData.getVin())) {
            realTimeData.setVin(null);
        }
        QueryWrapper<RealTimeData> query = Wrappers.query(realTimeData);
        query.orderByDesc("DATA_TIME");
        return R.ok(realTimeDataService.page(page, query));
    }

    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(realTimeDataService.getById(id));
    }

    @GetMapping("/getAllForMap")
    public R getAllForMap() {
        return R.ok(realTimeDataService.getAllForMap());
    }

    @PostMapping("/{id}/update")
    public R updateTerminal(@PathVariable("id") Integer id,
                    @RequestBody UpdateBms updateBms) {
        return realTimeDataService.updateTerminal(id, updateBms);
    }

    @GetMapping("/{id}/version")
    public R updateTerminal(@PathVariable("id") Integer id) {
        return realTimeDataService.queryVersion(id);
    }

}

